package com.example.otto.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    //当前跨域请求最大有效时长
    private static final long MAX_AGE = 24*60*60;

    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfigration = new CorsConfiguration();
        corsConfigration.addAllowedOrigin("http://localhost:8080"); //访问源地址
        corsConfigration.addAllowedHeader("*"); //访问请求头
        corsConfigration.addAllowedMethod("*"); //访问请求方法
        corsConfigration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**",corsConfigration); //对接口配置跨域
        return new CorsFilter(source);
    }
}
